import ScrollBarLayout from '@/components/ScrollBarLayout';
import moment from 'moment';
import Cls from 'classnames';
import { useContext, useEffect, useMemo, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { DescriptionsType } from '@/components/DescriptionsType';
import { changeNumMoneyToChinese, wordHandChildParam, wordToChildParams, getKeyRouter, getTenantID, getPosIDs, getUserID } from '@/utils';
import { getUpdateConfig } from '../mconfig/UpdateConfig';
import { connect, history } from 'umi';
import { Col, Form, Row, Spin, message, Tabs, Button, Space, Card, Modal } from 'antd';
import { CheckCircleOutlined, SaveOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { OpenMaterialModal } from '../mconfig/OpenMaterialModal';
import { AssetDiscardContext, IAcquisitionActionEnum, useAcquisitionManageReducer } from '../mconfig';
import { addStorageService, approvedAssetDiscardSerivice, editStorageService, getDetailService } from '../services';
import { ILoadMapTypeAll } from '@/common';
import { WorkflowChedkRecord, WorkflowHndTaskBtn, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import '../common/style.less';
import { BGflowBusinessType, orderType, requestController } from '../common/Format';
import { DetailInfoViewBottomBtn } from '../mconfig/DetailInfoViewBottomBtn';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import { create } from 'lodash';

const AcceptUpdateView: React.FC<any> = ({ curRes, locationProps }) => {
  /** 引入上下文 */
  const { materielList, acquisitionDispatch } = useAcquisitionManageReducer();
  /** 样式根目录 */
  const styleFixCls = 'contract-styfixcls-';

  /** 表单数据 */
  const [acceptForm] = Form.useForm();

  const [saveFlag, setSaveFlag] = useState<boolean>(false);

  /** 打开选择物料列表 */
  const [openMaterialModal, setOpenMaterialModal] = useState<boolean>(false);
  // 详情数据
  const [detailInfo, setDetailInfo] = useState<any>({});
  /** 报废审批同意判断是否可以调用同步接口 */
  const [auditSuccessState, setAuditSuccessState] = useState(false);

  /**是否显示撤销弹窗*/
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/

  // 工作流
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  // 打开物料选择弹窗
  const openMaterialModalStatus = () => {
    setOpenMaterialModal(true);
  };

  /**
   * 处理工作流功能 权限
   */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1001`) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1001`;
    const taskHandInfo: Record<string, any> = detailInfo?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [detailInfo]);

  /**
   * 新增编辑回调
   * @param res 接口返回数据
   * @param callType true 为新增回调  || false 为编辑回调
   */
  const updateAnnounceCallback = (res: any) => {
    if (res && res?.msgFlag) {
      if (saveFlag) {
        setWorkFlowInfoObj({
          selectFlowRows: res?.obj,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      } else {
        message.success(res?.msg);
        history.push({
          pathname: '/assetDiscardController/manage',
          state: {
            delRouterNameSource: history.location.pathname,
          },
        });
      }
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 获取详情回调
   * @param res 接口返回数据
   */
  const updataGetDetail = (res: any) => {
    if (res && res?.msgFlag) {
      const {
        obj: { massetApplyNumberList },
      } = res;
      message.success(res.msg || '获取详情成功');
      // 详情数据
      setDetailInfo({
        ...res?.obj,
        // createTime: moment(res?.obj.createTime),
      });
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_MATERIEL,
        payload: massetApplyNumberList,
      });

      /** 是否是审核中 */
      if (
        res?.obj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000` &&
        res?.obj?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_HANDLE_STATUS}1001`
      ) {
        setAuditSuccessState(true);
      }
    } else {
      message.error(res.msg || '获取详情失败');
    }
  };

  // // 获取入库详情
  const { getDetailLoading, getDetailRun } = getDetailService(updataGetDetail);
  // // 提交入库申请
  const { addStorageLoading, addStorageRun } = addStorageService(updateAnnounceCallback);
  // // 编辑入库申请
  const { editStorageLoading, editStorageRun } = editStorageService(updateAnnounceCallback);
  /** 报废-最后一个人审核通过后调用的同步接口 */
  const { approvedAssetDiscardUseRun, approvedAssetDiscardUseLoading } = approvedAssetDiscardSerivice((res) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      // history.push({
      //   pathname: '/assetDiscardController/manage',
      //   state: {
      //     delRouterNameSource: history.location.pathname,
      //   },
      // });
    } else {
      message.error(res?.msg);
    }
  });

  /** 获取表单配置
   *  @pageType  传递的类型，是修改还是查看
   *  @record   当前项
   */
  const { config, methods } = getUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? (detailInfo ? Object.assign({}, locationProps?.state?.record, detailInfo) : locationProps?.state?.record) : {},
    handleMaterialModal: openMaterialModalStatus,
    formName: acceptForm,
  });

  /** 暂存按钮  保存数据 */
  const handleSave = (flag: boolean) => {
    // 对表单进行校验，获取表单数据
    acceptForm.validateFields()?.then((values: any) => {
      if (!materielList?.length) {
        return message.error('资产详情不能为空！');
      }
      // 处理数据  id 变换字段
      const tempList = materielList?.map((item: any) => {
        item.materialOrAssetId = locationProps?.state?.pageType == 'add' ? item.id : item.materialOrAssetId;
        return item;
      });
      const params = {
        ...values,
        createTime: moment(values?.createTime).format('YYYY-MM-DD HH:mm:ss'), // 申请日期
        massetApplyNumberList: tempList || [], // 物料信息列表
        state: `${getTenantID()}${ILoadMapTypeAll.STORAGE_HANDLE_STATUS}1000`, // 新增或者编辑时  单据状态
        businessType: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1014`, // 资产报废流程类型
        // createTime: moment(values?.createTime).format('YYYY-MM-DD HH:mm:ss'),
      };
      setSaveFlag(flag);
      // 新增和修改接口
      if (locationProps?.state?.pageType == 'add') {
        addStorageRun(params);
      } else {
        params.id = locationProps?.state?.record?.id; // 修改 id
        editStorageRun(params);
      }
    });
  };

  /** 申请页ref */
  const { confirm } = Modal;

  /** 关闭当前页 */
  const handleClose = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationProps?.state?.returnPathName,
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  /** 返回tab子页面 */
  const tabsItem = () => {
    let items: any[] = [
      {
        label: '资产报废',
        key: '001',
        children: (
          <>
            <div className="commonTabsBodyDom">
              <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
                <ScrollBarLayout style={{ padding: '5px 20px' }}>
                  <DescriptionsType config={config} />
                </ScrollBarLayout>
              </div>
              <div className="tabsBodyBottomBtn">
                <Space>
                  <>
                    {/* {locationProps?.state?.pageType !== 'detail' || (detailInfo?.state == '100124161000' && detailInfo?.checkState == '100199021003') ? (
                      <Button
                        type={'primary'}
                        // icon={<SaveOutlined />}
                        onClick={() => handleSave(false)}
                      >
                        暂存
                      </Button>
                    ) : null} */}
                    {((!detailInfo?.state ||
                      (detailInfo?.state == '100124161000' && !detailInfo?.checkState) ||
                      (detailInfo?.state == '100124161002' && detailInfo?.checkState == '100199021003')) &&
                      detailInfo?.createrID == getUserID()) ||
                    locationProps?.state?.pageType === 'add' ? (
                      <Button type={'primary'} onClick={() => handleSave(true)}>
                        提交
                      </Button>
                    ) : null}

                    <Button danger onClick={handleClose}>
                      关闭
                    </Button>
                  </>
                  {/* 流程节点弹框 */}
                  {/* {locationProps?.state?.pageType == 'detail' ? (
                    <WorkflowHndTaskBtn
                      flowDetailInfo={detailInfo}
                      detailInfoObj={detailInfo}
                      reloadCallback={() => {
                        getDetailRun(detailInfo?.id);
                      }}
                      requestController={'assetApplyHandle'}
                      flowBusinessType={BGflowBusinessType()}
                    />
                  ) : null} */}
                </Space>
              </div>
            </div>
          </>
        ),
      },
    ];
    return items;
  };

  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  // 获取详情
  useEffect(() => {
    if (locationProps?.state?.pageType != 'add') {
      getDetailRun(locationProps?.state?.record?.id);
    }
  }, []);

  /** 监听审核状态 */
  useEffect(() => {
    if (
      auditSuccessState &&
      detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` &&
      detailInfo?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_HANDLE_STATUS}1003`
    ) {
      approvedAssetDiscardUseRun({
        ...detailInfo,
        workflowResult: true,
        createTime: moment(detailInfo?.newCreateTime).format('YYYY-MM-DD HH:mm:ss'),
      });
    }
  }, [detailInfo?.checkState, detailInfo?.state, auditSuccessState]);

  const changeRevoke = () => {
    setInvalidState({
      isShow: true,
      resObj: detailInfo,
    });
  };

  /** tabs 标签页操作 */
  const contactsTabsExtra = () => {
    return (
      <DetailInfoViewBottomBtn
        changeRevoke={changeRevoke}
        position="top"
        detailInfo={detailInfo}
        getDetailRun={getDetailRun}
        locationProps={locationProps}
        handleSave={handleSave}
      />
    );
  };

  return (
    <>
      <AssetDiscardContext.Provider
        value={{
          rightTableProps: {
            dataSource: [],
            materielForm: {},
            loading: false,
            getAcquisitionTableData: ({}) => {},
            mapList: [],
            pagination: {},
            otherParams: {},
            searchList: [],
            reloadTableData: () => {},
          },
          curRes,
          materielList,
          acquisitionDispatch,
        }}
      >
        <div className={'apply-update-UpdataIntentBox'}>
          <Spin spinning={addStorageLoading || editStorageLoading || getDetailLoading}>
            <Row className={`${styleFixCls}row`}>
              <Col span={24} className={`${styleFixCls}row-col`}>
                <Tabs
                  className={pageStyles['commonTabs']}
                  type="card"
                  onChange={(activeKey: string) => {}}
                  items={tabsItem()}
                  destroyInactiveTabPane={true}
                  tabBarExtraContent={contactsTabsExtra()}
                />
              </Col>
            </Row>

            <div>
              {/* 选择资产列表 */}
              {openMaterialModal && (
                <OpenMaterialModal
                  isShowModal={openMaterialModal}
                  onClose={() => {
                    setOpenMaterialModal(false);
                  }}
                />
              )}
            </div>

            {/* 工作流-----审批记录 */}
            {detailInfo?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1014`] && (
              <WorkflowChedkRecord
                curRes={curRes}
                dataDetailInfo={detailInfo}
                flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1014`}
                requestController={requestController()}
                reloadPageCallback={() => {
                  // getDetailRun({ id: detailInfo?.id });
                }} // 刷新方法-详情方法
                revokeStateID={`${getTenantID()}${ILoadMapTypeAll?.STORAGE_HANDLE_STATUS}1000`}
                allBtnFuncQuqry={workflowPowerAllBtn}
                tabPaneHeight={0.35}
                isCheckDrawer={true}
                isShowCollapse={isShowWorkRecord}
                changeCollapse={(val) => {
                  setIsShowWorkRecord(val);
                }}
                cancelStateId={`${getTenantID()}${ILoadMapTypeAll?.STORAGE_HANDLE_STATUS}1004`}
                isSyncArchive={true}
              />
            )}

            {/* 工作流-----发起流程审批弹窗 */}
            {workFlowInfoObj?.showWorkFlowModal && (
              <WorkflowSwitchModal
                openVisible={workFlowInfoObj?.showWorkFlowModal}
                businessInfoObj={workFlowInfoObj?.selectFlowRows}
                requestController={requestController()}
                orderType={workFlowInfoObj?.selectFlowRows?.orderType || orderType()}
                category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1014`}
                // businessCategory={`${getTenantID()}${ILoadMapTypeAll.INTENTION_CATEGORY}1000`}
                businessCategory={``}
                selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
                reloadInfoCallback={() => {
                  // getDetailRun({ id: detailInfo?.id });
                  history.push({
                    pathname: '/assetDiscardController/manage',
                    state: {
                      delRouterNameSource: history.location.pathname,
                    },
                  });
                }}
                openFlowChangeModal={setShowSwitchFlow}
                onClose={() => {
                  setWorkFlowInfoObj({
                    ...workFlowInfoObj,
                    showWorkFlowModal: false,
                  });
                  history.push({
                    pathname: '/assetDiscardController/manage',
                    state: {
                      delRouterNameSource: history.location.pathname,
                    },
                  });
                }}
                replaceStrObj={{ own: 'own', workflowType: 'category' }}
              />
            )}

            {/* 撤销弹窗 */}
            {invalidState?.isShow && (
              <RevokeModal
                resObj={invalidState?.resObj}
                revokeRequestUrl={'/assetApplyHandle/revoke'}
                onClose={() => setInvalidState({})}
                reqBody={{ id: invalidState?.resObj?.id, state: `${getTenantID()}${ILoadMapTypeAll?.STORAGE_HANDLE_STATUS}1000` }}
                modalTip={
                  <div style={{ color: '#000' }}>
                    确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.applyTitle}</span>】的审核, 撤销后可重新提交！
                  </div>
                }
                reloadRequest={() => {
                  history.push({
                    pathname: locationProps?.state?.returnPathName,
                    state: {
                      delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
                      returnPathName: locationProps?.state?.returnPathName,
                    },
                  });
                }}
              />
            )}

            {/* 挑选流程组件 */}
            {showSwitchFlow && (
              <WorkflowNoDefaultTable
                openVisibleSwitch={showSwitchFlow}
                onCloseSwitch={closeSwitchFlowModal}
                requestController={'purchaseSourceIntentController'}
                orderType={workFlowInfoObj?.selectFlowRows?.orderType || orderType()}
                category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1014`}
                // businessCategory={`${getTenantID()}${ILoadMapTypeAll.INTENTION_CATEGORY}1000`}
                businessCategory={``}
                saveSelectFlowID={(flowId: string) => {
                  setWorkFlowInfoObj({
                    ...workFlowInfoObj,
                    saveNoDefaultFlowID: flowId,
                  });
                }}
                selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
              />
            )}
          </Spin>
        </div>
      </AssetDiscardContext.Provider>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(AcceptUpdateView);
